package com.supermap.shiro.config.shiro;

import com.supermap.shiro.auth.entity.AppUser;
import com.supermap.shiro.auth.service.AppUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import javax.annotation.Resource;

/**
 * @author xiaolu
 * @date 2018/7/2 上午10:11
 */
public class AuthRealm extends AuthorizingRealm {

    @Resource
    private AppUserService appUserService;

    /**
     * 认证.登录
     * @param token 用户token
     * @return AuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的token
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;
        String username = utoken.getUsername();
        String password = new String(utoken.getPassword());
        AppUser user = appUserService.login(username,password);
        //解决MD5大小写加密
        user.setPassword(user.getPassword().toLowerCase());
        //放入shiro.调用CredentialsMatcher检验密码
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
//        //获取session中的用户
//        User user=(User) principal.fromRealm(this.getClass().getName()).iterator().next();
//        List<String> permissions=new ArrayList<>();
//        Set<Role> roles = user.getRoles();
//        if(roles.size()>0) {
//            for(Role role : roles) {
//                Set<Module> modules = role.getModules();
//                if(modules.size()>0) {
//                    for(Module module : modules) {
//                        permissions.add(module.getModuleName());
//                    }
//                }
//            }
//        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //将权限放入shiro中.
//        info.addStringPermissions(permissions);
        return info;
    }

}